from hashlib import md5
import os

from dotenv import load_dotenv
from sqlmodel import SQLModel, Session, create_engine

from db.crud import check_user_exists, create_user
from fastapi import Depends
from typing import Annotated
from db.models import Log, Message, User  # 新增此行

######数据库相关配置#####
# MySQL连接配置
load_dotenv("../../.env")
MYSQL_USER = os.getenv("MYSQL_USER", "root")
MYSQL_PASSWORD = os.getenv("MYSQL_PASSWORD", "hdtx2022")
MYSQL_HOST = os.getenv("MYSQL_HOST", "127.0.0.1")  # 或你的MySQL服务器地址
MYSQL_PORT = int(os.getenv("MYSQL_PORT", "3306"))  # 默认MySQL端口
MYSQL_DBNAME = os.getenv("MYSQL_DBNAME", "base_station")
# SQLALCHEMY_DB_URI = "sqlite:///./db2.db"
SQLALCHEMY_DB_URI = f"mysql+pymysql://{MYSQL_USER}:{MYSQL_PASSWORD}@{MYSQL_HOST}:{MYSQL_PORT}/{MYSQL_DBNAME}"

# 创建引擎
engine = create_engine(
    SQLALCHEMY_DB_URI,
    pool_size=5,  # 连接池大小
    max_overflow=10,  # 超出连接池大小后可打开的连接数
    pool_timeout=30,  # 获取连接的超时时间(秒)
    pool_recycle=3600,  # 连接回收时间(秒)
    echo=True,  # 显示SQL语句(调试用)
)


# 依赖注入 AsyncSession
def get_db() -> Session:
    with Session(engine) as db:
        yield db


# 定义依赖项，方便在 FastAPI 路由中使用
get_session_dependency = Annotated[Session, Depends(get_db)]


def init_db() -> None:
    SQLModel.metadata.create_all(engine)
    db = Session(engine)
    if not check_user_exists(db, "admin"):
        create_user(db=db, uname="admin", pwd=md5(b"123456").hexdigest(), role=0)


def close_db() -> None:
    engine.dispose()  # 释放连接池中的所有连接，关闭相关会话资源。
